package com.roc.web.action.excel;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.roc.newPage.IPageService;
import com.roc.page.BaseSearchCondition;
import com.roc.page.PaginationBaseAction;
import com.roc.pojo.Operators;
import com.roc.pojo.TblClearTxn;
import com.roc.service.IExcelService;
import com.roc.service.IMerchantServices;
import com.roc.service.IPagenitionService;
import com.roc.service.operator.IPowerInfoService;
import com.roc.util.Constance;
import com.roc.util.Utils;
import com.roc.util.constant.ConfigProperties;
import com.roc.util.constant.Constant;
import com.roc.util.constant.Role;
import com.roc.web.action.setting.ClearSearchCondition;

@Component
@Scope("prototype")
@Namespace("/clearExcel")
@SuppressWarnings("all")
public class ClearExcelAction extends PaginationBaseAction{
	static Logger  logger=Logger.getLogger(ClearExcelAction.class);
	@Autowired
	IExcelService excelService;
	private ClearSearchCondition searchCondition;
	private InputStream excelFile;
	private String  excelName;
	@Autowired
	IPagenitionService pagenitionService;
	
	@Autowired 
	IMerchantServices merchantServices;
	
	@Autowired
	private IPowerInfoService powerInfoService;
	
	protected Map<String,String> tranMap = ConfigProperties.getSysDB1("TRANS_CD",false);
	
	@Action(value="clearExcel",results = {@Result(name="success",type="stream"
			,params = { "contentType", "application/vnd.ms-excel", "inputName",  
			            "excelFile","contentDisposition",  "attachment;filename=${excelName}.xls",
 "bufferSize", "1024*3" }),@Result(name="error",location="/pages/setting/clearlist.jsp") }) 
	public String clearExcel(){
		try{
			if(searchCondition.getMinDate()==null || searchCondition.getMinDate().trim().length()==0){
				addActionError("请选择清算起始日期！");
				return ERROR;
			}
			if(searchCondition.getMaxDate()==null || searchCondition.getMaxDate().trim().length()==0){
				addActionError("请选择清算终止日期！");
				return ERROR;
			}
			
			boolean isTrue=Constance.theDateIsTrue(searchCondition.getMinDate(),searchCondition.getMaxDate());
			if(!isTrue){
				addActionError("您选择的清算日期必须在一个月之内！");
				return ERROR;
			}
			Operators op=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);

			Map<String, String> map=powerInfoService.queryRealIdByOpId(op.getSuperiorId(), op.getRoleType(), op.getId(), op.getOrgCode());
	           // String orgCode=map.get("orgCode");
	         String superRole= map.get("superRole");
	         String opRealId =map.get("opRealId");
			// 查询 当前代理商及子代理商 数据
			searchCondition.setRoleType(superRole);
			if(Role.MERCHANT.getCode().equals(superRole)){
				searchCondition.setMerId(op.getAccountNo());
			}else if(Role.AGENT.getCode().equals(superRole)||Role.SFB_AGENT.getCode().equals(superRole)){
				
				String agentId= opRealId;
				searchCondition.setAgentId(agentId);
				
			}else if(Role.AGENT_BUSS.getCode().equals(superRole)){
				searchCondition.setOpId(opRealId);
			}else if(Role.MARKET_DIRECT.getCode().equals(superRole) || Role.MARKET_LEAD.getCode().equals(superRole)){
				searchCondition.setMarketorId(opRealId);
			}else if(Role.O_MANAGER.getCode().equals(superRole)){//
				searchCondition.setUcbccdArea(op.getOneagentid());
			}/*else if(Role.OPERATORS_COMM.getCode().equals(op.getRoleType()) && !Constant.SD_ORG_CD.equals(op.getOneagentid())){//运维人员
				searchCondition.setUcbccdArea(op.getOneagentid());
			}*/
			searchCondition.setOrgCode(op.getOrgCode());
			
			List<TblClearTxn> clearList = new ArrayList<TblClearTxn>();
			int rows = pagenitionService.countSQL(searchCondition);
			if (rows > 0) {
				searchRsList = pagenitionService.findAllSQL(searchCondition,
						calcuStart(getCurrentPage()),rows);
				if (searchRsList != null && searchRsList.size() > 0) {
					Iterator iterator = searchRsList.iterator();
					while (iterator.hasNext()) {
						
						Object[] obj = (Object[]) iterator.next();
						TblClearTxn clear = new TblClearTxn();
					
						if (obj[0] != null && !"".equals(obj[0])) {
							clear.setMchtCd(obj[0].toString());
						}
						if (obj[1] != null && !"".equals(obj[1])) {
							clear.setMchtName(obj[1].toString());
						}
						if (obj[2] != null && !"".equals(obj[2])) {
							clear.setTermId(obj[2].toString());
						}
						if (obj[3] != null && !"".equals(obj[3])) {/*
							clear.setPan(obj[3].toString());*/
							// 主账号隐藏中间数字
							clear.setPan(Utils.dealCardNo(Constance.Null2EmptyTrim(obj[3].toString())));
						}
						if (obj[4] != null && !"".equals(obj[4])) {
							clear.setStlmDate(obj[4].toString());
						}
						if (obj[5] != null && !"".equals(obj[5])) {
							clear.setTransDateTime(Utils.getTime(obj[5].toString()));
						}
						if (obj[6] != null && !"".equals(obj[6])) {
							clear.setTransAmt(obj[6].toString());
						}
						if (obj[7] != null && !"".equals(obj[7])) {
							clear.setMchtFee(obj[7].toString());
						}
						if (obj[8] != null && !"".equals(obj[8])) {
							clear.setMchtSetAmt(obj[8].toString());
						}
						if (obj[9] != null && !"".equals(obj[9])) {
							clear.setMaSettleDtStr(obj[9].toString());
						}
						if (obj[10] != null && !"".equals(obj[10])) {
							clear.setTxnDesc(tranMap.get(obj[10].toString()));
						}
						if (obj[11] != null && !"".equals(obj[11])) {
							clear.setSysSer(obj[11].toString());
						}
						if (obj[12] != null && !"".equals(obj[12])) {
							clear.setCardKindDis(obj[12].toString());
						}
						clearList.add(clear);
					}
				}
			}
			
			HSSFWorkbook work=excelService.clearTransQueryExcel(clearList,searchCondition.getMinDate(),searchCondition.getMaxDate());
			 ByteArrayOutputStream output = new ByteArrayOutputStream();  
			         work.write(output);  
			   
			        byte[] ba = output.toByteArray();  
			         excelFile = new ByteArrayInputStream(ba);  
			         output.flush();  
			         output.close();  
			         
		}catch(Exception e){
			logger.info("######清算导出Excel失败######");
			addActionError(e.getMessage());
			return ERROR;
		}
		return SUCCESS;
	}
	
	public InputStream getExcelFile() {
		return excelFile;
	}
	public void setExcelFile(InputStream excelFile) {
		this.excelFile = excelFile;
	}
	public String getExcelName() {
		String excelName="清算明细表"+Constance.formateDate();
		 
			try {
				excelName = new String(excelName.getBytes(),"ISO8859-1");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
				logger.info("生成excel名称失败了！");
			}
		 
		return  excelName;
		
	}
	public void setExcelName(String excelName) {
		this.excelName = excelName;
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSession() {
		return (ClearSearchCondition) getSession().getAttribute(
				SEARCH_SESSION_BEAN_CALCU);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.roc.page.PaginationBaseAction#getSearchConditionFromSubClass()
	 */
	@Override
	protected BaseSearchCondition getSearchConditionFromSubClass()
			throws Exception {
		return searchCondition;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.roc.page.PaginationBaseAction#setSearchConditionToSubClass(com.roc.page.BaseSearchCondition)
	 */
	@Override
	protected void setSearchConditionToSubClass(
			BaseSearchCondition searchCondition) throws Exception {
		this.setSearchConditionToSubClass(searchCondition);
	}

	public ClearSearchCondition getSearchCondition() {
		return searchCondition;
	}

	public void setSearchCondition(ClearSearchCondition searchCondition) {
		this.searchCondition = searchCondition;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.roc.page.PaginationBaseAction#setSearchToConditionSession(com.roc.page.BaseSearchCondition)
	 */
	@Override
	protected void setSearchToConditionSession(
			BaseSearchCondition searchCondition) {
		getSession().setAttribute(SEARCH_SESSION_BEAN_CALCU, searchCondition);
	}

	@Override
	protected String getInitPageSize() {
		return null;
	}
	
	
}
